package com.jt.service.impl;

import com.jt.mapper.FileMapper;
import com.jt.service.FileService;
import com.jt.vo.ImageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource(value="classpath:/properties/image.properties",encoding = "utf-8")
public class FileServiceImpl implements FileService {
    @Autowired
    private FileMapper fileMapper;

    //定义文件存储的根目录
    @Value("${image.fileLocalDir}")
    private String fileLocalDir;//="D:/JT-SOFT/images";
    @Value("${image.urlPath}")
    private String urlPath;
    private static Set<String> typeSet=new HashSet<>();
    static {
        typeSet.add(".jpg");
        typeSet.add(".png");
        typeSet.add(".gif");
    }
    //实现文件上传
    @Override
    public ImageVo upload(MultipartFile uploadFile) {
        //获取图片文件名称
        String fileName = uploadFile.getOriginalFilename();
        fileName = fileName.toLowerCase();//转成小写
        //获取图片类型(获取后缀类型)
        int index = fileName.lastIndexOf(".");
        String fileType = fileName.substring(index);
        if(!typeSet.contains(fileType)){
            return ImageVo.fail();
        }

        //获取图片对象类型
        try {
            BufferedImage read = ImageIO.read(uploadFile.getInputStream());
            int width = read.getWidth();
            int height = read.getHeight();
            if(width==0||height==0){
                return ImageVo.fail();
            }

            // 分目录进行存储
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
            String dateDir = simpleDateFormat.format(new Date());
            String fileDir=fileLocalDir+dateDir;
            File imageFileDir = new File(fileDir);
            if(!imageFileDir.exists()){//目录不存在，动态生成
                imageFileDir.mkdirs();
            }

            // 防止文件重名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String realFileName=uuid+fileType;
            File realFile = new File(fileDir + realFileName);
            uploadFile.transferTo(realFile);

            //String url = "https://img14.360buyimg.com/n0/jfs/t1/112052/9/3699/127886/5ea9598dE40977b56/d3813bc086108a0b.jpg";
            String url=urlPath+dateDir+realFileName;
            return ImageVo.success(url, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVo.fail();
        }

    }

}
